<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../react18/react.development.js"></script>
    <script src="../react18/react-dom.development.js"></script>
    <script src="../react18/babel.min.js"></script>
    <script src="../react18/prop-types.js"></script>
</head>

<body>
    <div id="app"></div>
    <script type="text/babel">
        //用类式组件的方式定义根组件
        class App extends React.Component {
            //保存一些数据,state和表单输入数据双向绑定
            state = {
                name: "zhangsan",
                age: 20,
                hobby: "浪里个浪"
            }
            render() {
                //结构数据并返回虚拟DOM，统一监听每个表单填写信息，一般用onChange
                const { name, age, hobby } = this.state
                return (
                    <div>
                        姓名： <input type="text" value={name} onChange={this.changeForm("name")} />
                        <br />
                        年龄： <input type="text" value={age} onChange={this.changeForm("age")} />
                        <br />
                        爱好： <input type="text" value={hobby} onChange={this.changeForm("hobby")} />
                        <br />
                        <button onClick={this.handle}>提交</button>
                    </div>
                )
            }

            //需要获取表单输入的值和state中对应的属性名来设置关联
            //如果直接把changeForm作为事件函数，则页面一开始渲染就会被触发，无法获取输入框中的新信息
            //[变量]=>属性名表达式
            changeForm = (type) => {
                //state中数据相关标识可以通过传参传进来
                console.log(type);
                //获取当前事件对应的虚拟DOM
                return (e) => {
                    if ([type] === "age") {
                        this.setState({
                            [type]: +e.target.value
                        })
                    } else {
                        this.setState({
                            [type]: e.target.value
                        })
                    }

                }

            }

            handle = () => {
                const { name, age, hobby } = this.state
                console.log(name, age, hobby);
            }
        }

        const root = ReactDOM.createRoot(document.getElementById("app"))
        root.render(<App />)
    </script>
</body>

</html>